//Package lengthconv performs Inch and Meter conversions.
package lengthconv

import (
	"flag"
	"fmt"
)

type Inch float64
type Meter float64

const (
	OneInch Inch = 0.0254
)

func (i Inch) String() string {
	return fmt.Sprintf("%gIN", i)
}

func (m Meter) String() string {
	return fmt.Sprintf("%gM", m)
}

type meterFlag struct{ Meter }

func (f *meterFlag) Set(s string) error {
	var unit string
	var value float64
	fmt.Sscanf(s, "%f%s", &value, &unit) // no error check needed
	switch unit {
	case "M", "m":
		f.Meter = Meter(value)
		return nil
	case "IN", "in":
		f.Meter = InchToMeter(Inch(value))
		return nil
	}
	return fmt.Errorf("invalid length %q", s)
}

func MeterFlag(name string, value Meter, usage string) *Meter {
	f := meterFlag{value}
	flag.CommandLine.Var(&f, name, usage)
	return &f.Meter
}
